<template>
  <Row style="direction: rtl">
    <Button type="primary" shape="round" @click="onCopyScript" style="direction: ltr"><copy-filled /> 复制脚本</Button>
  </Row>
  <Row>
    <pre id="scripts" :style="contentStyle">
<template v-for="item of dmls"><i v-if="item.indexOf('--') != -1">{{item}}</i><p v-else @click="copyDML(item)">{{item}}</p></template>
      </pre>
  </Row>
</template>

<script setup>
  import { useStore } from 'vuex';
  import { ref, inject, watch, computed, onMounted } from 'vue';
  import { Row, Button } from 'ant-design-vue';
  import { CopyFilled } from '@ant-design/icons-vue';

  const $store = useStore();
  const $http = inject('$http');
  const $message = inject('$message');
  const $copyText = inject('$copyText');

  const props = defineProps({
    dbIndex: String,
    dbType: String,
    schema: String,
    tableName: String
  });

  const dmls = ref([]);

  const contentStyle = computed(() => {
    let maxHeight = $store.state.area.content.height - 130 + 'px';

    return {
      'min-height': maxHeight,
      'max-height': maxHeight
    };
  });

  watch(
    () => props.tableName,
    () => GetTableDDL()
  );

  function GetTableDDL() {
    let dbIndex = props.dbIndex;
    let dbType = props.dbType;
    let schema = props.schema;
    let tableName = props.tableName;

    if (dbIndex && schema && tableName) {
      $http.get(`/api/db/${dbIndex}/${schema}/${tableName}/dml`).then(res => (dmls.value = res.datas));
    }
  }

  function copyDML(text) {
    $copyText(text).then(() => {
      $message.success('脚本片段已复制！');
    });
  }

  function onCopyScript() {
    $copyText(document.getElementById('scripts').innerText).then(() => {
      $message.success('脚本已复制！');
    });
  }

  onMounted(() => {
    GetTableDDL();
  });
</script>

<style lang="less" scoped>
  #scripts {
    i {
      font-weight: bold;
      user-select: none;
    }

    p {
      cursor: pointer;
      user-select: all;
    }
  }
</style>
